import {Bluetooth} from './core'; // 导入您提供的蓝牙库
import { CRCAlgorithm } from './crc-checker';

// 解析遥控器数据（根据GY/T 407—2024标准）
function parseRemoteControlData(buffer: ArrayBuffer) {
  const view = new DataView(buffer);
  const type = view.getUint8(0) & 0b11; // 取最低两位判断广播类型
  if (type === 0) {
    // 广播类型1（配对广播）
    return {
      type: 'pairing',
      capability: view.getUint8(1),
      txPower: view.getInt8(2)
    };
  } else if (type === 1) {
    // 广播类型2（回连/唤醒）
    return {
      type: view.getUint8(0) & 0b10000 ? 'wakeup' : 'reconnect',
      sourceAddr: Array.from(new Uint8Array(buffer, 1, 3)).join(':'),
      targetAddr: Array.from(new Uint8Array(buffer, 4, 3)).join(':')
    };
  }
}


// 定义目标设备的服务UUID和特征UUID
const REMOTE_CONTROL_SERVICE_UUID = '00001812-0000-1000-8000-00805F9B34FB';
const COMMAND_CHARACTERISTIC_UUID = '00002A4D-0000-1000-8000-00805F9B34FB';
const NOTIFY_CHARACTERISTIC_UUID = '00002A4E-0000-1000-8000-00805F9B34FB';

// 蓝牙设备缓存管理器
class BluetoothDeviceCache {
  private static instance: BluetoothDeviceCache;
  private cachedDevices: Map<string, BluetoothDevice> = new Map();

  private constructor() {}

  public static getInstance(): BluetoothDeviceCache {
    if (!BluetoothDeviceCache.instance) {
      BluetoothDeviceCache.instance = new BluetoothDeviceCache();
    }
    return BluetoothDeviceCache.instance;
  }

  public cacheDevice(deviceId: string, device: BluetoothDevice): void {
    this.cachedDevices.set(deviceId, device);
  }

  public getCachedDevice(deviceId: string): BluetoothDevice | undefined {
    return this.cachedDevices.get(deviceId);
  }

  public clearDevice(deviceId: string): void {
    this.cachedDevices.delete(deviceId);
  }

  public clearAll(): void {
    this.cachedDevices.clear();
  }
}

// 初始化蓝牙实例
const bluetooth = new Bluetooth({
  deviceNameFilter: /MyRemoteControl/,
  rssiThreshold: -70,
  mtuSize: 512,
  splitterOptions: {
    crcAlgorithm: CRCAlgorithm.CRC16_CCITT,
    chunkSize: 512
  }
});

// 获取缓存管理器实例
const deviceCache = BluetoothDeviceCache.getInstance();

// 监听关键事件
bluetooth
  .on('deviceFound', (device) => {
    console.log('发现设备:', device.name, device.deviceId, `RSSI:${device.RSSI}dBm`);
  })
  .on('connectionStateChange', ({ deviceId, connected }) => {
    console.log(`设备 ${deviceId} ${connected ? '已连接' : '已断开'}`);
    if (!connected) {
      deviceCache.clearDevice(deviceId);
    }
  })
  .on('data', ({ value }) => {
    console.log('收到原始数据:', new Uint8Array(value));
  })
  .on('fullData', (fullData) => {
    console.log('完整数据包:', parseRemoteControlData(fullData));
  });

// 检查并连接缓存的设备
async function connectCachedDevice(deviceId: string): Promise<boolean> {
  try {
    const cachedDevice = deviceCache.getCachedDevice(deviceId);
    if (!cachedDevice) return false;

    // 检查是否已连接
    const isConnected = await bluetooth.isConnected(deviceId);
    if (isConnected) return true;

    // 重新连接
    await bluetooth.connect(deviceId);
    await bluetooth.startNotification(REMOTE_CONTROL_SERVICE_UUID, NOTIFY_CHARACTERISTIC_UUID);
    return true;
  } catch (err) {
    console.error('连接缓存设备失败:', err);
    deviceCache.clearDevice(deviceId);
    return false;
  }
}

// 主流程
async function main() {
  try {
    await bluetooth.init();

    // 1. 尝试连接缓存中的设备
    const cachedDeviceIds = Array.from(deviceCache.getCachedDevices().keys());
    if (cachedDeviceIds.length > 0) {
      const connected = await connectCachedDevice(cachedDeviceIds[0]);
      if (connected) {
        console.log('成功连接缓存设备');
        return;
      }
    }

    // 2. 扫描新设备
    const devices = await bluetooth.scanDevices({ timeout: 5000 });
    if (devices.length === 0) throw new Error('未找到匹配设备');

    // 3. 连接新设备并缓存
    const targetDevice = devices[0];
    await bluetooth.connect(targetDevice.deviceId);
    deviceCache.cacheDevice(targetDevice.deviceId, targetDevice);
    await bluetooth.startNotification(REMOTE_CONTROL_SERVICE_UUID, NOTIFY_CHARACTERISTIC_UUID);

    // 4. 发送命令
    const enterLowLatencyCmd = new Uint8Array([0x02, 0x01]).buffer;
    await bluetooth.write(REMOTE_CONTROL_SERVICE_UUID, COMMAND_CHARACTERISTIC_UUID, enterLowLatencyCmd, { crc: true });

    // 5. 发送大尺寸数据
    const largeData = new Uint8Array(1024).fill(0xaa).buffer;
    await bluetooth.sendLargeData(REMOTE_CONTROL_SERVICE_UUID, COMMAND_CHARACTERISTIC_UUID, largeData);
  } catch (err) {
    console.error('蓝牙操作失败:', err);
  }
}

// 发送数据到已连接设备
async function sendDataToConnectedDevice(data: ArrayBuffer): Promise<boolean> {
  try {
    const connectedDevices = bluetooth.getConnectedDevices();
    if (connectedDevices.length === 0) return false;

    const deviceId = connectedDevices[0];
    await bluetooth.write(REMOTE_CONTROL_SERVICE_UUID, COMMAND_CHARACTERISTIC_UUID, data, { crc: true });
    return true;
  } catch (err) {
    console.error('发送数据失败:', err);
    return false;
  }
}

// 页面跳转后恢复连接
async function restoreConnection(): Promise<boolean> {
  const cachedDeviceIds = Array.from(deviceCache.getCachedDevices().keys());
  if (cachedDeviceIds.length === 0) return false;

  return await connectCachedDevice(cachedDeviceIds[0]);
}

// 执行主流程
main();




